package com.example.backblog.service.oauth;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.example.backblog.service.oauth.dto.GiteeUser;
import com.example.backblog.service.oauth.dto.ProviderToken;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.apache.coyote.Request;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class GiteeProviderService {
    /**
     * 根据用户授权信息获取当前用户的 accessToken
     * 对用户进行授权，先创建一个GET请求，请求gitee中对应用户的访问令牌
     * @param providerToken 用户授权信息
     * @return 当前用户的 accessToken
     */
    public String getGiteeToken(ProviderToken providerToken) {
        //1. 创建http请求，构建请求体和请求url等，并向gitee发起请求
        OkHttpClient client = new OkHttpClient();

        String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code=" + providerToken.getCode()
                + "&client_id=" + providerToken.getClientId()
                + "&redirect_uri=" + providerToken.getRedirectUri()
                + "&client_secret=" + providerToken.getClientSecret();
        String response = HttpUtil.createPost(url)
                .contentType("application/json")
                .body(JSON.toJSONString(providerToken)).execute().body();

        String tokenStr = response;
        String accessToken = tokenStr.split(",")[0].split(":")[1];
        accessToken = accessToken.substring(1, accessToken.length() - 1);
        return accessToken;
    }

    /**
     * 根据用户的 access token 获取当前gitee用户的详细信息
     * @param accessToken 用户的访问令牌
     * @return gitee用户对象
     */
    public GiteeUser getGiteeUser(String accessToken) {
        //1. 构建http的GET请求，向gitee请求用户数据
        String response = HttpUtil.get("https://gitee.com/api/v5/user?access_token=" + accessToken);
        String giteeUserStr = response;
        return JSON.parseObject(giteeUserStr, GiteeUser.class);

    }
}
